// 基础服务类，提供通用的API请求方法
import { message } from 'antd';
import { get, post, put, del } from '../util/api';

export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  page?: number;
  pageSize?: number;
  total?: number;
  totalPages?: number;
}

export interface ListParams {
  page?: number;
  pageSize?: number;
  [key: string]: any;
}

export abstract class BaseService<T> {
  protected baseUrl: string;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  /**
   * 获取列表数据
   */
  async getList(params?: ListParams): Promise<ApiResponse<T[]>> {
    try {
      return await get(this.baseUrl, { params });
    } catch (error) {
      this.handleError('获取列表失败', error);
      throw error;
    }
  }

  /**
   * 获取单个详情
   */
  async getById(id: string | number): Promise<ApiResponse<T>> {
    try {
      return await get(`${this.baseUrl}/${id}`);
    } catch (error) {
      this.handleError('获取详情失败', error);
      throw error;
    }
  }

  /**
   * 创建数据
   */
  async create(data: Partial<T>): Promise<ApiResponse<T>> {
    try {
      const result = await post(this.baseUrl, data);
      message.success('创建成功');
      return result as ApiResponse<T>;
    } catch (error) {
      this.handleError('创建失败', error);
      throw error;
    }
  }

  /**
   * 更新数据
   */
  async update(id: string | number, data: Partial<T>): Promise<ApiResponse<T>> {
    try {
      const result = await put(`${this.baseUrl}/${id}`, data);
      message.success('更新成功');
      return result as ApiResponse<T>;
    } catch (error) {
      this.handleError('更新失败', error);
      throw error;
    }
  }

  /**
   * 删除数据
   */
  async delete(id: string | number): Promise<ApiResponse<void>> {
    try {
      const result = await del(`${this.baseUrl}/${id}`);
      message.success('删除成功');
      return result as ApiResponse<void>;
    } catch (error) {
      this.handleError('删除失败', error);
      throw error;
    }
  }

  /**
   * 批量删除
   */
  async batchDelete(ids: (string | number)[]): Promise<ApiResponse<void>> {
    try {
      const result = await post(`${this.baseUrl}/batch-delete`, { ids });
      message.success('批量删除成功');
      return result as ApiResponse<void>;
    } catch (error) {
      this.handleError('批量删除失败', error);
      throw error;
    }
  }

  /**
   * 错误处理
   */
  protected handleError(operation: string, error: any): void {
    console.error(`${operation}:`, error);
    const errorMessage = error?.message || '操作失败，请稍后重试';
    message.error(`${operation}: ${errorMessage}`);
  }
}